<?php

namespace App\Http\Controllers;

use App\Interfaces\SmsService;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class LoginController extends Controller
{
    public function index(){
        return view('mobile.login.index');
    }
    public function login(Request $request,SmsService $sms){

        $phone = $request->input('phone');
        $mesCode = $request->input('mescode');

        $validator=Validator::make($request->all(),[
            'phone'=>'required'
        ],[
            'phone.required'=>'请填写手机号',

        ]);
        if ($validator->fails()){
            return response()->json(['code'=>0,'message'=>$validator->errors()->first('phone')]);
        }

        if(!$sms->validateRegCode(Session::get('MsgCode_id'),$mesCode)){
            return response()->json(['code'=>0,'message'=>'手机验证码不正确或验证码已过期']);
        }
        //判断是否有手机号
       $user= User::where('mobile',$phone)->first();
       if($user){
           Auth::loginUsingId($user->id);
           return response()->json(['code'=>1,'message'=>'登陆成功']);
       }else{
           return response()->json(['code'=>0,'message'=>'用户不存在']);
       }
    }
}
